Ext.namespace("DesignConfig");
var testProcess = "";

var DesignConfig = {
		//初始化布局
		init : function(){		
			tip = "提示";
		//全局变量
		currentBtn = "select";
		currentParam = "base";
		//--- 图形化设计 ---
		lineFlag = false;
		dragable = true;
		eventsrc = null;//eventsrc是当前触发事件的对象（节点对象）
		presrc = null; //前一个选中的对象
		xmlNode = null;//当前选中的XML节点
		x = 0,y = 0;  
		popeventsource = "";
		temp1 = 0;
		temp2 = 0;
		//--- 画线 ---
		//连线的源和目标
		srcRect=null,desRect=null;
		x0=0,x1=0,y0=0,y1=0;   //连线的头尾坐标
		fontX=0,fontY=0;	   //文字的坐标
		xml = null;//xml对象
		//各个节点所拥有的属性
		nodeParams = {
			base:["base","form"],//文本节点
			mail:["base","mailto"],//mail节点
			process:["base","form"],//流程定义
			start:["base"],//start、end节点
			task:["base","change"],//任务节点
			transition:["base"]//transition
		}
		//虚线
		dashLine = null;
		dvSVG = null
		//显示xml窗口
		xmlWin = null;
		designWin = null;
		var elePanel = new Ext.Panel({
			title: '工具栏',
			region: 'west',	
			iconCls: 'picon05',
			width: 150,
			split: true,
			minSize: 150,
			maxSize: 150,
			contentEl: 'west',
			collapsible: true			
		});
		var mainPanel = new Ext.Panel({
			region: 'center',
			autoScroll: true,
			contentEl: 'center',
		});

		designWin = new Ext.Window({
			layout: 'border',
			iconCls: 'picon06',
			width: 900,
	        height: 600,
	  		autoScroll: false,
	        plain: false,
	  		modal: true,
	  		//maximizable: true,
	  		closable: false,
			maximized: true,
	  		closeAction: 'hide',
			items:[elePanel,mainPanel]
		});
		designWin.show();
		Ext.getDom("west").style.display = "block";
		//初始流程属性
		initProcess();
		//为工具栏按钮注册事件，点击工具栏是触发事件
		Ext.get(Ext.DomQuery.select(".btn")).on("click",function(){
			if(!Ext.fly(this).hasClass("btn_down")){
				currentBtn = this.title;
				Ext.get(Ext.DomQuery.select(".btn_down")).removeClass("btn_down");
				Ext.fly(this).addClass("btn_down");
				setParams();
			}
		});
Ext.getBody().on('mousedown',function(e){
			//判断是否是右键
			if(e.buttons != "2")
				return false;
			
			target = e.target;
			//判断是否在center区域
			if(!Ext.get(target).findParent("div[id=center]",Ext.getBody()))
				return false;
			if (e.target.tagName.toLowerCase() == 'textbox') 
				target = event.srcElement.parentElement;
			if (e.target.tagName.toLowerCase() == 'b') 
				target = event.srcElement.parentElement.parentElement;			
			var tagName = target.tagName.toLowerCase();
			if (tagName != "line" && tagName != "roundrect" && tagName != "span")
				return false;
			contextmenu.showAt(e.getXY());
		});
		//document.onselectstart = function(){return false;}//禁用复制事件
		document.onmousedown = downAction;  //开始移动
		document.onmouseup = upAction;  //结束移动
	},
	winShow : function(){
		designWin.show();
	}
};
//初始设置流程定义
function initProcess(){	
	presrc = null;
	if(xml == null){
		//节点计数器
		taskNum = 1;
		lineNum = 1;
		endNum = 1;
		boolNum = 1;
		joinNum = 1;
		forkNum = 1;
		mailNum = 1;
		//树列表计数器
		swimlaneNum = 1;
	}
	// 创建SVG
	createSVGopen()
	createDashLine();
	//设置显示属性
}
//根据点击的按钮设置参数
function setParams(){
	switch(currentBtn){
		case "select":
			dragable = true;
			break
		case "grid":
			break
		case "transition":
			lineFlag = true;
			break
		default:
	}
}
//左键按下时方法
function downAction(){
	//判断是否是左键被按下
	if(event.buttons != 1)
		return;
	switch(currentBtn){
		case "select":		
			//拖动
			drags();
			//显示属性
			showParams();
			break
		case "transition":
			document.querySelector("svg").addEventListener('mousedown',createLine())
			break
		default:
			createNode();
	}
}
//左键释放时方法
function upAction(){
	if(!Ext.get(eventsrc).findParent("div[id=center]",Ext.getBody()))
		return false;
		
	switch(currentBtn){
		case "select":
			dragable = false;
			break
		case "transition":
			drawLine();
			break
		default:
	}
}
//创建节点
function createNode(){
	if(!nodeOrNot())
	return false;
	const x = event.x + Ext.getDom("center").parentNode.scrollLeft-200;
	const y = event.y + Ext.getDom("center").parentNode.scrollTop-70;
	let svgNS = "http://www.w3.org/2000/svg"
	let shapeElement;
	var oG = document.createElementNS(svgNS,'g');
	oG.style.curosr='pointer';
	shapeElement = document.createElementNS(svgNS,'rect');
	shapeElement.setAttribute("x", x);
	shapeElement.setAttribute("y", y);
	shapeElement.setAttribute("rx", "5");
	shapeElement.setAttribute("width", '100');
	shapeElement.setAttribute("height", "50");
	shapeElement.setAttribute("fill", '#eee');
	shapeElement.setAttribute("stroke-width", '1');
	shapeElement.setAttribute("stroke", '#000');
	// shapeElement.setAttribute("cursor", 'pointer');
	var startimg = document.createElementNS(svgNS,'image')
	startimg.setAttribute("x", x+8);
	startimg.setAttribute("y", y);
	startimg.setAttribute("width", '18');
	startimg.setAttribute("height", '29');
	// startimg.setAttribute("cursor", 'pointer');
	var oText = document.createElementNS(svgNS,'text');
	oText.setAttribute('x',x+60);
	oText.setAttribute('y',y+20);
	oText.setAttribute('font-size','14px');
	oText.setAttribute('fill','#000');
	oText.setAttribute('text-anchor','middle');
	// oText.setAttribute("cursor", 'pointer');
	oG.classList.add('node')

	switch(currentBtn){
		case "start":
			oG.id = 'start';
			oG.flowtype = "start"
			shapeElement.id = 'start'
			startimg.setAttribute('href','images/icon/start.gif');
			oText.innerHTML="流程开始";
			oG.appendChild(shapeElement);
			oG.appendChild(oText);
			oG.appendChild(startimg);
			document.getElementById("DBsvg").appendChild(oG);
			break
		case "task":
			oG.id = "task" + taskNum;
			oG.flowtype = "task"
			shapeElement.id = "task" + taskNum;
			startimg.setAttribute('href','images/icon/task.gif');
			oText.innerHTML= "任务节点" + taskNum;;
			taskNum ++;	
			break
		case "end":
			oG.id = "end" + endNum;
			oG.flowtype = "end";
			shapeElement.id = "end" + endNum;
			startimg.setAttribute('href','images/icon/end.gif');
			oText.innerHTML= "流程结束";
			endNum ++;
			break;
		default:
	}
	oG.appendChild(shapeElement);
	oG.appendChild(oText);
	oG.appendChild(startimg);
	document.getElementById("DBsvg").appendChild(oG);
}
//判断是否创建节点
function nodeOrNot(){
	//点击事件事是否发生在工作区
	//防止右键菜单弹出时点击阴影出错
	if(event.srcElement == null) return false;
	if(event.srcElement.id != "DBsvg")
		return false;
	//如果是start节点判断是否已经存在
	if(currentBtn == "start" && document.getElementById("start") != null){
		return false;
	}
	return true;
}
//将当前触发事件的节点内对象转为节点对象
function selectNode(){
	eventsrc = event.srcElement;
	//如果事件对象是textbox，将事件对象变为它的父对象
	if (event.srcElement.tagName.toLowerCase() == 'rect') 
		eventsrc = event.srcElement.parentElement;
	//如果事件对象是b，将事件对象变为它的父对象的父对象
	if (event.srcElement.tagName.toLowerCase() == 'b') 
		eventsrc = event.srcElement.parentElement.parentElement;
		
	//如果是选择并且在center区域，执行下面的选中
	if(currentBtn == "select" && !!Ext.get(eventsrc).findParent("div[id=center]",Ext.getBody())){
		//如果前次选择与当前选中一致，不执行以下语句
		//alert(presrc.id + "," + eventsrc.id);
		if(presrc == eventsrc)
			return false;	
		if(presrc != null){
			if(presrc.tagName.toLowerCase() == "g"){
				// presrc.style.border = "0";
				presrc.style.stroke = ""
			}else{
				presrc.style.stroke = "#000"
				presrc.strokeColor = "#27548d";
				presrc.strokeWeight = "1pt";
				presrc.style.zIndex = 1;
			}
		}
		switch(eventsrc.tagName.toLowerCase()){
			case "g":
				eventsrc.style.border = "2";
				eventsrc.style.stroke = "#000"
				break
			case "line":
				eventsrc.strokeColor = "#ff0000";
				eventsrc.strokeWeight = "2pt";
				break
			case "span":
				eventsrc.style.border = "2px solid #ff0000";
				break
		}
		//将当前节点赋值给presrc
		presrc = eventsrc;
	}else if(currentBtn == "select"){
		if(presrc!=null&&eventsrc.tagName.toLowerCase()=="div"&&eventsrc.firstChild.id=="center"||eventsrc.id =="center"){
			if(presrc.tagName.toLowerCase() == "span"){
				presrc.style.border = "0";
			}else{
				presrc.strokeColor = "#27548d";
				presrc.strokeWeight = "1pt";
				presrc.style.zIndex = 1;
			}
			presrc = null;
		}
	}
}
function move(){
	if (event.buttons == 1 && dragable){
		let nx = event.clientX
		let ny = event.clientY
		var newleft = nx-x
		var newtop = ny-y
		// 获取盒子模型位置
		// //重新设置节点的坐标
		newNodeAttr(eventsrc,"g",nx-180,ny-80);
		nx = event.x;
		ny = event.y;
		//重画与节点相关的线和文字节点
		reDrawLine();
		return false;
	}
}
function newNodeAttr(node,title,left,top){
	eventsrc.childNodes.forEach(el=>{
		const tagname = el.tagName.toLowerCase()
		switch(tagname){
				case "rect":
					el.setAttribute("x",left,);
					el.setAttribute("y",top,);
					break
			    case "text":
					el.setAttribute("x",left+60,);
					el.setAttribute("y",top+20,);
					break
				case "image":
					el.setAttribute("x",left+8,);
					el.setAttribute("y",top,);
					break
			}
	})
}
function lineMove(){
	// 移动时的虚线随鼠标移动
	if(lineFlag){
		const line = dashLine.lastChild
		line.setAttribute('x2', event.offsetX);
		line.setAttribute('y2', event.offsetY);
		return false;
	}
}
//查看选择节点的属性
function showParams(){
	if(presrc==null&&eventsrc.tagName.toLowerCase()=="div"&&eventsrc.firstChild.id=="center"||eventsrc.id =="center"){
		//如果前次选中为null的话，显示流程定义属性
		initProcess();
		return false;
	}
	if(!Ext.get(eventsrc).findParent("div[id=center]",Ext.getBody()))
		return false;
	switch(eventsrc.flowtype){
		case "start":
			showNodeParams(nodeParams.start,"开始节点","picon08");
			break
		case "end":
			showNodeParams(nodeParams.start,"结束节点","picon09");
			break
		case "task":			
			showNodeParams(nodeParams.task,"任务节点","picon02");
			break
		case "transition":		
			showNodeParams(nodeParams.transition,"转换","picon03");
			break
		default:
			//当选中的是文本节点的话，转换成对应的连线
			eventsrc = Ext.getDom(eventsrc.title);
			showNodeParams(nodeParams.transition,"转换","picon03");
			break
	}
	//设置显示属性
}
//显示各节点对应的属性
function showNodeParams(params,title,icon){
	//隐藏所有属性
	Ext.get(Ext.DomQuery.select(".key_btn")).setDisplayed("none");
	//显示对应属性
	for(var i=0;i<params.length;i++){
		var param = Ext.DomQuery.select("div[title="+params[i]+"]")[0];
		if(params[i] == "base"){
			param.click();
		}
	}
}
function drags(){
	if (event.buttons != 1)
		return;
	selectNode();
	if (eventsrc.tagName.toLowerCase() == 'g'){
		dragable = true;
	
		temp1 = eventsrc.getBBox().x;
		temp2 = eventsrc.getBBox().y;
		x = event.x;
		y = event.y;
		document.onmousemove = move;
	}
}
//创建虚线
function createDashLine(){
   
	if(document.getElementById("lines") == null){
		dashLine = document.createElementNS("http://www.w3.org/2000/svg",'g');
		dashLine.id = "lines";
		dashLine.setAttribute("stroke-dasharray", '5 5');
		const defs = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
		const marker = document.createElementNS('http://www.w3.org/2000/svg', 'marker');
		marker.setAttribute('id', 'arrow');
		marker.setAttribute('markerWidth', 10);
		marker.setAttribute('markerHeight', 10);
		marker.setAttribute('refX', 4);
		marker.setAttribute('refY', 2);
		marker.setAttribute('orient', 'auto');
		const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
		path.setAttribute('d', 'M0,0 L5,2 L0,4 z');
		path.setAttribute('fill', '#000');
		marker.appendChild(path);
		defs.appendChild(marker);
		dashLine.appendChild(defs);
		document.getElementById("DBsvg").appendChild(dashLine);
	}
}
function createSVGopen(){
	if(document.getElementById("DBsvg") == null){
		dvSVG = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
		dvSVG.setAttribute("width", "100%")
		dvSVG.setAttribute("height", "100%")
		dvSVG.setAttribute("id", "DBsvg")
		document.getElementById("center").appendChild(dvSVG);
	}
}
function createLine() {
	selectNode();
	if (eventsrc.tagName == 'g' && eventsrc.flowtype != "end"){
		srcRect = eventsrc;
		const dashLine = document.querySelector('#lines');
		const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
		line.stroke = 'black'
		line.setAttribute('x1', event.offsetX);
		line.setAttribute('y1', event.offsetY);
		line.setAttribute('x2', event.offsetX);
		line.setAttribute('y2', event.offsetY);
		line.setAttribute('stroke', 'black');
		line.setAttribute('stroke-width', '2');
		dashLine.appendChild(line);
		document.onmousemove = lineMove;
	}else{
		srcRect = null;
	}
}
function drawLine(){
	if(srcRect == null)
		return;
	selectNode();
	
	const lined = lines.lastChild;
	
	if(eventsrc.tagName != 'g'){
		eventsrc = event.srcElement.parentElement;
	}
	if (eventsrc.tagName == 'g' && srcRect != eventsrc){
		desRect = eventsrc;
		//创建线
		//判断是否画线
		if(drawOrNot()){
			direction();
			lined.setAttribute('x1', x0);
			lined.setAttribute('y1', y0);
			lined.setAttribute('x2', x1);
			lined.setAttribute('y2', y1);
			lined.setAttribute('marker-end',"url(#arrow)");
			lined.setAttribute('project', desRect.id);
			lined.setAttribute('source', srcRect.id);
			lined.source = srcRect.id;
			lined.project = desRect.id;
			lined.style.position = "absolute";
			lined.style.display = "block";
			lined.flowtype = "transition";
			lined.style.cursor = "pointer";
			lined.id = "line" + lineNum;
			lineNum ++;
			lined.setAttribute("stroke-dasharray", '0 0');
			lines.appendChild(lined)
		}else{
			lines.removeChild(lined);
		}
	}
	else{
        lines.removeChild(lined);
	}
	document.onmousemove = null;

	//onmouseup事件后隐藏虚线和取消移动事件
	// lines.style.display = "none";
}
function reDrawLine(){
	var lines = Ext.DomQuery.select("line[project="+eventsrc.id+"]").concat(Ext.DomQuery.select("line[source="+eventsrc.id+"]"));
	for(var i=0;i<lines.length;i++){
		if(eventsrc.id == lines[i].source){
			//将源与目的赋值为线的源与目的
			srcRect = document.getElementById(lines[i].source);
			desRect = document.getElementById(lines[i].project);
			direction();
			lines[i].setAttribute('x1', x0);
			lines[i].setAttribute('y1', y0);
			lines[i].setAttribute('x2', x1);
			lines[i].setAttribute('y2', y1);
			//重新设置文本位置
			fontLocation();
			var font = Ext.DomQuery.select("span[title="+lines[i].id+"]")[0];
			if(font != null){
				modifyXmlNodeAttr(lines[i],"g",fontX+","+fontY);
				font.style.pixelLeft = fontX;
				font.style.pixelTop = fontY;
			}
		}
		if(eventsrc.id == lines[i].project){
			//将源与目的赋值为线的源与目的
			srcRect = document.getElementById(lines[i].source);
			desRect = document.getElementById(lines[i].project);
			var locations = direction();
			lines[i].setAttribute('x1', x0);
			lines[i].setAttribute('y1', y0);
			lines[i].setAttribute('x2', x1);
			lines[i].setAttribute('y2', y1);
			//重新设置文本位置
			fontLocation();
			var font = Ext.DomQuery.select("span[title="+lines[i].id+"]")[0];
			if(font != null){
				//在修改坐标前先修改XML中的坐标，否则改完后找不到相应的节点
				modifyXmlNodeAttr(lines[i],"g",fontX+","+fontY);
				font.style.pixelLeft = fontX;
				font.style.pixelTop = fontY;
			}	
		}		
	}
}
//判断是否画线
function drawOrNot(){
	//目的地址不能是start
	if(desRect.flowtype == "start")
		return false;
	//是否已存在
	var lines = document.getElementsByTagName('line');
	for(var i=0;i<lines.length;i++){
		if(srcRect.id==lines[i].source&&desRect.id==lines[i].project)
			return false;
	}
	return true;
}
//在横线上生成文字
function createFont(){
	var textNode = document.createElement("span");
	fontLocation();
	textNode.style.pixelLeft = fontX;
	textNode.style.pixelTop = fontY;
	//textNode.innerHTML = "to " + desRect.title;   // 线上的字不显示
	Ext.fly(textNode).addClass("font_node");
	textNode.title = "line" + lineNum;
	textNode.id = "text" + lineNum;
	document.getElementById("center").appendChild(textNode);
	return textNode;
}
//判断文字的位置
function fontLocation(){
	fontX = Math.round(x0+(x1-x0)/2 - 30);
	fontY = Math.round(y0+(y1-y0)/2 - 25);
}
//箭头方向判断
function direction(){
	const srcRectBox = srcRect.getBBox()
	const desRectBox = desRect.getBBox()
	if(srcRectBox.x > desRectBox.x){
		if((srcRectBox.x - desRectBox.x) <= desRectBox.width){
			x0 = srcRectBox.x + srcRectBox.width / 2
			x1 = desRectBox.x + desRectBox.width / 2
			if(srcRectBox.y > desRectBox.y){
				y0 = srcRectBox.y;
				y1 = desRectBox.y + desRectBox.height;
			}else{
				y0 = srcRectBox.y + srcRectBox.height
				y1 = desRectBox.y;
			}
		}else{
			x0 = srcRectBox.x;
			x1 = desRectBox.x + desRectBox.width
			y0 = srcRectBox.y + srcRectBox.height / 2;
			y1 = desRectBox.y + desRectBox.height / 2;
		}
	}else{
		if ((desRectBox.x - srcRectBox.x) <= desRectBox.width){
			x0 = srcRectBox.x + srcRectBox.width / 2;
			x1 = desRectBox.x + desRectBox.width / 2;
			if (srcRectBox.y >  desRectBox.y){
			   y0 = srcRectBox.y;
			   y1 = desRectBox.y  + desRectBox.y;
			}else{
			   y0 = srcRectBox.y + srcRectBox.height;
			   y1 = desRectBox.y;
			}
		}else{
			x0 = srcRectBox.x + srcRectBox.width;
			x1 = desRectBox.x;
			y0 = srcRectBox.y + srcRectBox.height / 2;
			y1 = desRectBox.y + desRectBox.height / 2;
		}
	}
}
//修改节点对应的属性
function modifyXmlNodeAttr(node,param,value){
	node = findXmlNode(node);

	if(node != null)
		node.setAttribute(param,value);
}


